package com.css.fxfzypg.modules.baseData.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.common.utils.CheckObjFields;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.baseData.dto.PetIndProjectDto;
import com.css.fxfzypg.modules.baseData.dto.TraProjectDto;
import com.css.fxfzypg.modules.baseData.entity.KeyProjectEntity;
import com.css.fxfzypg.modules.baseData.repository.KeyProjectRepository;
import com.css.fxfzypg.modules.baseData.repository.TraProjectRepository;
import com.css.fxfzypg.modules.baseData.service.TrarPojectService;
import com.css.fxfzypg.modules.baseData.vo.TraProjectVo;
import com.css.fxfzypg.util.EasyPoiExcelUtil;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.util.UUIDGenerator;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author
 * @date 2022/10/6 11:06
 * @description
 **/
@Slf4j
@Service
public class TraProjectServiceImpl implements TrarPojectService {
    @Autowired
    private KeyProjectRepository keyProjectRepository;

    @Autowired
    private TraProjectRepository traProjectRepository;

    @Autowired
    private SysAreaService sysAreaService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public String importTraProject(MultipartFile file, ImportParams params, String dkpKeyType) {
        Map<String,String> areaIdCodeMap = (Map<String,String>) JSONObject.parse(redisTemplate.opsForValue().get(FxfzConstants.CACHE_SYS_KEY  +"areaIdCodeMap"));
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            ExcelImportResult<TraProjectVo> result = ExcelImportUtil.importExcelMore(file.getInputStream(), TraProjectVo.class, params);

            List<TraProjectVo> list = result.getList();
            if (PlatformObjectUtils.isNotEmpty(list)) {
                for (TraProjectVo item : list) {
                    String str = item.getDkpLongOrSpanOrScale();
                    String dkpTransType = item.getDkpTransType();
                    KeyProjectEntity KeyProject = new KeyProjectEntity();
                    BeanUtils.copyProperties(item, KeyProject);
                    String divisionIds = null;

                    //判断省市县的名称是否符合规范
                    divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(item.getDkpProvince(), "utf-8"),
                            URLEncoder.encode(item.getDkpCity(), "utf-8"),
                            URLEncoder.encode(item.getDkpPrefecture(), "utf-8"));
                    if(StringUtils.isBlank(divisionIds) || divisionIds.split("_").length<3){
                        return "导入失败，请检查"+item.getDkpProvince()+","+item.getDkpCity()+","+item.getDkpPrefecture()+"数据正确性";
                    }
                    String[] split = divisionIds.split("_");
                        if ("独立特长隧道工程、越江隧道、海底隧道".equals(dkpTransType)) {
                            KeyProject.setDkpLong(str);
                            KeyProject.setDkpTransType(FxfzConstants.SPECIALITY_TUNNEL);
                        } else if ("跨度大于150m或其它技术复杂、修复困难的铁路桥梁".equals(dkpTransType)) {
                            KeyProject.setDkpSpan(str);
                            KeyProject.setDkpTransType(FxfzConstants.COMPLEX_BRIDGE);
                        } else if ("在城市轨道交通网络中占据关键地位、承担交通量大的大跨度桥梁和车站的主体结构".equals(dkpTransType)) {
                            KeyProject.setDkpScale(str);
                            KeyProject.setDkpTransType(FxfzConstants.CRUX_BRIDGE);
                        } else if ("城市道路中悬索桥、斜拉桥以及跨度大于150m的拱桥".equals(dkpTransType)) {
                            KeyProject.setDkpSpan(str);
                            KeyProject.setDkpTransType(FxfzConstants.LONGSPAN_ARCH_BRIDGE);
                        } else if ("国际或国内主要干线机场的航管楼".equals(dkpTransType)) {
                            KeyProject.setDkpScale(str);
                            KeyProject.setDkpTransType(FxfzConstants.MAIN_CONTROL_TOWER);
                        }

                    KeyProject.setDkpProvinceId(split[0]);
                    KeyProject.setDkpCityId(split[1]);
                    KeyProject.setDkpPrefectureId(split[2]);
                    KeyProject.setDkpIsDelete(YNEnum.N.toString());
                    KeyProject.setDkpCreateUser(PlatformSessionContext.getUserID());
                    KeyProject.setDkpCreateTime(new Date());
                    KeyProject.setDkpId(UUIDGenerator.getUUID());
                    KeyProject.setDkpKeyType(dkpKeyType);
                    KeyProject.setProvinceCode(areaIdCodeMap.get(split[0]));
                    KeyProject.setCityCode(areaIdCodeMap.get(split[1]));
                    KeyProject.setPrefectureCode(areaIdCodeMap.get(split[2]));
                    keyProjectRepository.saveKeyProject(KeyProject);
                }
            }
            returnMsg.append("成功导入" + (result.getList().size()) + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<TraProjectVo> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    TraProjectVo peoVO = iterator.next();
                    KeyProjectEntity KeyProject = new KeyProjectEntity();
                    BeanUtils.copyProperties(peoVO, KeyProject);
                    if (CheckObjFields.isAllFieldNull(KeyProject)){
                        continue;
                    }
                    returnMsg.append("第" + peoVO.getRowNum() + "行 " + peoVO.getErrorMsg() + "<br/>");
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public void exportExcel(List<String> idList, HttpServletResponse response) {
        List<TraProjectDto> list=traProjectRepository.findInIdList(idList);
        try {
            for(TraProjectDto item:list){
                String dkpTransType = item.getDkpTransType();
                if(dkpTransType.equals(FxfzConstants.SPECIALITY_TUNNEL)){
                    item.setDkpTransType(castType(dkpTransType));
                    item.setDkpLongOrSpanOrScale(item.getDkpLong());
                }
                if(dkpTransType.equals(FxfzConstants.COMPLEX_BRIDGE)){
                    item.setDkpTransType(castType(dkpTransType));
                    item.setDkpLongOrSpanOrScale(item.getDkpSpan());
                }
                if(dkpTransType.equals(FxfzConstants.CRUX_BRIDGE)){
                    item.setDkpTransType(castType(dkpTransType));
                    item.setDkpLongOrSpanOrScale(item.getDkpScale());
                }
                if(dkpTransType.equals(FxfzConstants.LONGSPAN_ARCH_BRIDGE)){
                    item.setDkpTransType(castType(dkpTransType));
                    item.setDkpLongOrSpanOrScale(item.getDkpSpan());
                }
                if(dkpTransType.equals(FxfzConstants.MAIN_CONTROL_TOWER)){
                    item.setDkpTransType(castType(dkpTransType));
                    item.setDkpLongOrSpanOrScale(item.getDkpScale());
                }
            }

            List<TraProjectDto> dtoList = new ArrayList<>();
            for (String id : idList) {
                dtoList.addAll(list.stream().filter(l -> l.getDkpId().equals(id)).collect(Collectors.toList()));
            }
            EasyPoiExcelUtil.exportExcel(dtoList, "交通运输工程信息统计", "交通运输工程信息", TraProjectDto.class, "交通运输工程信息", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("导出成功");
    }

    @Override
    public void update(KeyProjectEntity keyProjectEntity) {
        String dkpTransType = keyProjectEntity.getDkpTransType();
        if(dkpTransType.equals(FxfzConstants.SPECIALITY_TUNNEL)){
            traProjectRepository.updateSpecialityTunnel(keyProjectEntity);
        }
        if(dkpTransType.equals(FxfzConstants.COMPLEX_BRIDGE)){
            traProjectRepository.updateCmplexBridge(keyProjectEntity);
        }
        if(dkpTransType.equals(FxfzConstants.CRUX_BRIDGE)){
            traProjectRepository.updateCruxBridge(keyProjectEntity);
        }
        if(dkpTransType.equals(FxfzConstants.LONGSPAN_ARCH_BRIDGE)){
            traProjectRepository.updateLongspanArchBridge(keyProjectEntity);
        }
        if(dkpTransType.equals(FxfzConstants.MAIN_CONTROL_TOWER)){
            traProjectRepository.updateMainControlTower(keyProjectEntity);
        }
    }

    /**
     * 数字值转换为对应汉字
     *
     * @param type
     * @return
     */
    private String castType(String type) {
        if (FxfzConstants.SPECIALITY_TUNNEL.equals(type)) {
            type = "独立特长隧道工程、越江隧道、海底隧道";
        }
        if (FxfzConstants.COMPLEX_BRIDGE.equals(type)) {
            type = "跨度大于150m或其它技术复杂、修复困难的铁路桥梁";
        }
        if (FxfzConstants.CRUX_BRIDGE.equals(type)) {
            type = "在城市轨道交通网络中占据关键地位、承担交通量大的大跨度桥梁和车站的主体结构";
        }
        if (FxfzConstants.LONGSPAN_ARCH_BRIDGE.equals(type)) {
            type = "城市道路中悬索桥、斜拉桥以及跨度大于150m的拱桥";
        }
        if (FxfzConstants.MAIN_CONTROL_TOWER.equals(type)) {
            type = "国际或国内主要干线机场的航管楼";
        }
        return type;
    }

}
